package com.lew.jlight.redis;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import redis.clients.jedis.BinaryJedis;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.exceptions.JedisException;

public class JedisUtils {

    private static final String OK_CODE = "OK";
    private static final String OK_MULTI_CODE = "+OK";
    private static Logger logger = LoggerFactory.getLogger(JedisTemplate.class);

    /**
     * 判断 返回值是否ok.
     */
    public static boolean isStatusOk(String status) {
        return (status != null) && (OK_CODE.equals(status) || OK_MULTI_CODE.equals(status));
    }

    /**
     * 在Pool以外强行销毁Jedis.
     */
    public static void destroyJedis(Jedis jedis) {
        if ((jedis != null) && jedis.isConnected()) {
            try {
                jedis.quit();
                jedis.disconnect();
            } catch (Exception e) {
                logger.error(e.getMessage(), e);
            }
        }
    }

    /**
     * Ping the jedis instance, return true is the result is PONG.
     */
    public static boolean ping(JedisPool pool) {
        JedisTemplate template = new JedisTemplate(pool);
        try {
            String result = template.execute(BinaryJedis::ping);
            return (result != null) && result.equals("PONG");
        } catch (JedisException e) {
            return false;
        }
    }
}
